package com.dkd.flow.strategy.service.operation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.dkd.common.core.domain.entity.SysUser;
import com.dkd.flow.context.ProcessContext;
import com.dkd.flow.context.ProcessContextBuilder;
import com.dkd.flow.domain.EProcessInstances;
import com.dkd.flow.domain.EProcessTask;
import com.dkd.flow.emums.FlowOperation;
import com.dkd.flow.emums.FlowStatus;
import com.dkd.flow.emums.TaskActionType;
import com.dkd.flow.emums.TaskStatus;
import com.dkd.flow.service.impl.EProcessTaskServiceImpl;
import com.dkd.flow.strategy.annotation.Strategy;
import com.dkd.flow.utils.RevokeUtils;
import com.dkd.flow.utils.TaskCreate;

import cn.hutool.core.util.IdUtil;

@Service
@Strategy(FlowOperation.RE_SUBMIT)
public class ReSubmitStrategy extends BaseStrategy {
    @Autowired
    ProcessContextBuilder processContextBuilder;
    @Autowired
    RevokeUtils revokeUtils;
    @Autowired
    TaskCreate taskCreate;
    @Autowired
    private EProcessTaskServiceImpl eProcessTaskServiceImpl;

    @Override
    public Long execute(JSONObject data) {
        // 使用构建器初始化上下文 --- start --- //
        ProcessContext context = processContextBuilder.build(data);
        EProcessInstances eProcessInstances = context.getEProcessInstances();
        EProcessTask curTask = context.getCurTask();
        Long curTaskStatus = context.getCurTaskStatus();
        EProcessInstances paramsEProcessInstances = context.getEProcessInstances();
        JSONObject formValue = context.getFormValue();
        Long processDefinitionId = context.getProcessDefinitionId();
        Long curTaskId = context.getCurTaskId();

        // 使用构建器初始化上下文 --- end --- //
        Long taskGroupId = taskCreate.createAndSetOperationGroupId(eProcessInstances);
        initNodeRelations(processDefinitionId);
        // 创建发起人重新发起的任务
        JSONObject launchNode = links.get(0)
                .getJSONObject("toNode");
        if (launchNode == null) {
            throw new RuntimeException("links 中第一个节点的 toNode 为 null，无法创建发起人任务");
        }
        SysUser liableUser = nodeUtils.getLiableUser(eProcessInstances);
        // 创建 发起人任务 INITIATOR_TASK 1 自己 重新提交 RE_SUBMIT 12 处理中 PROCESSING 1
        Long launchTaskId = IdUtil.getSnowflakeNextId();
        EProcessTask launchTask = taskCreate.createLaunchTask(eProcessInstances,
                launchNode,
                null,
                TaskStatus.RE_SUBMIT,
                launchTaskId,
                null,
                launchTaskId,
                liableUser,
                taskGroupId,
                JSONObject.toJSONString(formValue),
                TaskActionType.OPERATION_TASK);
        // 查找同组下的被驳回操作任务（OPERATION_TASK + RETURNED），排除当前操作任务
        java.util.List<EProcessTask> returnedTasks = taskCreate.getOperationTasks(curTask.getTaskGroupId(),
                curTask.getID(), TaskStatus.RETURNED);
        EProcessTask nextOperationTask = (returnedTasks != null && !returnedTasks.isEmpty())
                ? returnedTasks.get(0)
                : null;

        if (nextOperationTask != null) {
            Long approverTaskId = IdUtil.getSnowflakeNextId();
            taskCreate.approverTask(
                    eProcessInstances,
                    nodeUtils.getApproverByTask(nextOperationTask),
                    nextOperationTask.getProcessDesignId(),
                    TaskStatus.UNDER_APPROVAL,
                    approverTaskId,
                    launchTaskId,
                    null,
                    taskGroupId,
                    JSONObject.toJSONString(formValue),
                    TaskActionType.LOG_TASK);
            revokeUtils.createSynTasksWithStatus(
                    nextOperationTask,
                    eProcessInstances,
                    TaskStatus.UNDER_APPROVAL,
                    launchTaskId,
                    taskGroupId,
                    formValue,
                    TaskActionType.LOG_TASK);
            // 重置审批节点的审批数量
            resetEProcessInstancesApproverCount(eProcessInstances,
                    nextOperationTask.getProcessDesignId(),
                    0);

        }
        // 实例状态
        eProcessInstances.setFlowStatus(FlowStatus.PROCESSING.getValue().longValue());
        updateEProcessInstances(eProcessInstances);
        // 清除操作组ID
        taskCreate.clearOperationGroupId(eProcessInstances);
        // 返回主审批人任务ID（如果没找到下一个操作任务，返回null）
        return launchTask != null ? launchTask.getID() : null;
    }
}